package com.aviation.sell_ticket.controller;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aviation.sell_ticket.service.OrderService;
import com.aviation.sell_ticket.tool.IdCardUtil;
import com.aviation.sell_ticket.tool.ResultEnum;
import com.aviation.sell_ticket.tool.ResultUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("OrderAction")
public class OrderController {

    @Resource
    private OrderService orderService;

    @ResponseBody
    @RequestMapping("generateOrder")
    public Map<String,Object> generateOrder(@RequestBody JSONObject jsonObject, HttpServletRequest request){

        try {
            //提取数据
            String mailbox = JSON.toJSONString(jsonObject.get("mailbox"));
            String cityName = JSON.toJSONString(jsonObject.get("cityName"));
            String cityNameTwo = JSON.toJSONString(jsonObject.get("cityNameTwo"));
            JSONArray passengers = JSON.parseArray(JSON.toJSONString(jsonObject.get("Passengers")));
            JSONArray flights = JSON.parseArray(JSON.toJSONString(jsonObject.get("flights")));

            //判断数据是否正确
            if (Validator.isNull(mailbox) || Validator.isEmail(mailbox)) {
                return ResultUtil.success(ResultEnum.MAILBOX_ERROR, null);
            } else if (!Validator.isNull(passengers)) {

                //提取乘客信息并重新封装
                List<Map<String,String>> passengerList=new ArrayList<>();
                for (Object passenger : passengers) {

                    //提取数据并去除多余字符
                    Map<String,String> passengerMap=new HashMap<>();
                    JSONObject passengerl=JSON.parseObject(String.valueOf(passenger));
                    String name=JSON.toJSONString(passengerl.get("name"));
                    String IDCard=JSON.toJSONString(passengerl.get("IDCard"));
                    IDCard=IDCard.replace("\"","");
                    name=name.replace("\"","");

                    if(Validator.isNull(name) || name.equals("")){
                        return ResultUtil.success(ResultEnum.NAME_ERROR, null);
                    }else if(Validator.isNull(IDCard) || IDCard.equals("") || !IdCardUtil.isIdcard(IDCard)){
                        return ResultUtil.success(ResultEnum.ID_CARD_ERROR, null);
                    } else{
                        passengerMap.put("name",name);
                        passengerMap.put("IDCard",IDCard);
                        passengerMap.put("phone",JSON.toJSONString(passengerl.get("phone")).replace("\"",""));
                    }
                    passengerList.add(passengerMap);
                }

                if(!Validator.isNull(passengers)) {
                    //提取航班信息并重新封装
                    List<Map<String,Object>> flightsList=new ArrayList<>();
                    for (Object flight : flights) {

                        //提取数据并去除多余字符
                        Map<String,Object> flightsMap=new HashMap<>();
                        JSONObject flightl=JSON.parseObject(String.valueOf(flight));
                        int priceDifferentiation=Integer.parseInt(JSON.toJSONString(flightl.get("priceDifferentiation")));
                        String modelId=JSON.toJSONString(flightl.get("model_id"));
                        String flightId=JSON.toJSONString(flightl.get("flight_id"));
                        String departure=JSON.toJSONString(flightl.get("departure"));
                        departure=departure.replace("\"","");
                        modelId=modelId.replace("\"","");
                        flightId=flightId.replace("\"","");

                        String transfer=JSON.toJSONString(flightl.get("transfer")).replace("\"","");
                        String number=JSON.toJSONString(flightl.get("number")).replace("\"","");

                        if(priceDifferentiation>2 || priceDifferentiation<0){
                            return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                        }else if(Validator.isNull(modelId)){
                            return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                        }else if(Validator.isNull(flightId)){
                            return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                        } else if (Validator.isNull(transfer) || Validator.isNull(number)) {
                            return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                        } else if (!Validator.isNull(departure)){
                            flightsMap.put("priceDifferentiation",priceDifferentiation);
                            flightsMap.put("modelId",modelId);
                            flightsMap.put("flightId",flightId);
                            flightsMap.put("departure",departure);
                            flightsMap.put("transfer",transfer);
                            flightsMap.put("number",number);
                            flightsList.add(flightsMap);
                        }else {
                            return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                        }
                    }

                    //判断出发地与目的地是否为空
                    if(Validator.isNull(cityName) || cityName.equals("") || Validator.isNull(cityNameTwo) || cityNameTwo.equals("") || cityNameTwo.equals(cityName)){
                        return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                    }

                    //创建城市集合
                    List<String> city=new LinkedList<>();
                    city.add(cityName);
                    city.add(cityNameTwo);

                    //开始预定机票
                    return orderService.orderGenerated(mailbox,passengerList,flightsList,String.valueOf(request.getAttribute("userId")),city);
                }else{
                    return ResultUtil.success(ResultEnum.FLIGHT_NULL_ERROR, null);
                }

            }
        }catch (Exception e){
            return ResultUtil.beDefeated(ResultEnum.UNKNOWN_ERROR);
        }

        return ResultUtil.success(ResultEnum.PASSENGER_NULL_ERROR, null);
    }

    @ResponseBody
    @PostMapping("personalOrders")
    public Map<String,Object> personalOrders(HttpServletRequest request){
        return orderService.extractOrder(String.valueOf(request.getAttribute("userId")));
    }

    @ResponseBody
    @PostMapping("orderingInformation")
    public Map<String,Object> orderingInformation(HttpServletRequest request,String orderId){
        return orderService.orderingInformation(String.valueOf(request.getAttribute("userId")),orderId);
    }

    @ResponseBody
    @PostMapping("orderStatus")
    public Map<String,Object> orderStatus(HttpServletRequest request,String orderId){
        if(null==orderId){
            return ResultUtil.success(ResultEnum.ORDER_EXCEPTION, null);
        }
        return orderService.orderStatus(String.valueOf(request.getAttribute("userId")),orderId);
    }

    @ResponseBody
    @PostMapping("pay")
    public Map<String,Object> orderPay(HttpServletRequest request,String orderId){
        if(null==orderId){
            return ResultUtil.success(ResultEnum.ORDER_EXCEPTION, null);
        }
        return orderService.orderPay(String.valueOf(request.getAttribute("userId")),orderId);
    }

    @GetMapping("paymentCallback")
    public String paymentCallback(HttpServletRequest request) {
        return orderService.paymentCallback(request);
    }

    @PostMapping("returnTicket")
    @ResponseBody
    public Map<String,Object> returnTicket(HttpServletRequest request,String orderId){
        if(null==orderId){
            return ResultUtil.success(ResultEnum.ORDER_EXCEPTION, null);
        }
        return orderService.returnTicket(String.valueOf(request.getAttribute("userId")),orderId);
    }

}
